package com.example.Hongbao;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class FloatWindowService extends Service {

	/**
	 * 用于在线程中创建或移除悬浮窗。
	 */
	private Handler handler = new Handler();

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (!MyWindowManager.isWindowShowing()) {
			Log.i("fcy", "----------------- createBigWindow");
			handler.post(new Runnable() {
				@Override
				public void run() {
					MyWindowManager.createWindow(getApplicationContext());
				}
			});
		}

		return START_STICKY;

	}

	@Override
	public void onDestroy() {
		if (MyWindowManager.isWindowShowing()) {
			Log.i("fcy", "----------------- destroyWindow");
			handler.post(new Runnable() {
				@Override
				public void run() {
					MyWindowManager.removeWindow(getApplicationContext());
				}
			});
		}
		super.onDestroy();
	}

//	/**
//	 * 判断当前界面是否是桌面
//	 */
//	private boolean isHome() {
//		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
//		return getHomes().contains(rti.get(0).topActivity.getPackageName());
//	}
//
//	/**
//	 * 获得属于桌面的应用的应用包名称
//	 *
//	 * @return 返回包含所有包名的字符串列表
//	 */
//	private List<String> getHomes() {
//		List<String> names = new ArrayList<String>();
//		PackageManager packageManager = this.getPackageManager();
//		Intent intent = new Intent(Intent.ACTION_MAIN);
//		intent.addCategory(Intent.CATEGORY_HOME);
//		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
//			PackageManager.MATCH_DEFAULT_ONLY);
//		for (ResolveInfo ri : resolveInfo) {
//			names.add(ri.activityInfo.packageName);
//		}
//		return names;
//	}
}
